package games.gong.durid.exception;

import games.gong.durid.common.R;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.nio.file.AccessDeniedException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理参数验证异常（使用@Validated注解）
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<Map<String, Object>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, Object> response = new HashMap<>();
        Map<String, String> errors = new HashMap<>();

        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });

        logger.error("参数验证失败: {}", errors);
        response.put("errors", errors);
        response.put("message", "请检查以下必填字段");
        response.put("timestamp", LocalDateTime.now());
        return R.<Map<String, Object>>error(400, "参数验证失败").setData(response);
    }

    /**
     * 处理绑定异常
     */
    @ExceptionHandler(BindException.class)
    public R<Map<String, String>> handleBindException(BindException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });

        logger.error("参数绑定失败: {}", errors);
        return R.<Map<String, String>>error(400, "参数绑定失败").setData(errors);
    }

    /**
     * 处理约束违反异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public R<Set<ConstraintViolation<?>>> handleConstraintViolationException(ConstraintViolationException ex) {
        logger.error("约束违反异常: {}", ex.getMessage());
        return R.<Set<ConstraintViolation<?>>>error(400, "约束违反异常").setData(ex.getConstraintViolations());
    }

    /**
     * 处理访问拒绝异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public R<Void> handleAccessDeniedException(AccessDeniedException ex) {
        logger.error("访问被拒绝: {}", ex.getMessage());
        return R.error(HttpStatus.FORBIDDEN.value(), "访问被拒绝");
    }

    /**
     * 处理其他所有异常
     */
    @ExceptionHandler(Exception.class)
    public R<Void> handleGenericException(Exception ex) {
        logger.error("系统异常: ", ex);
        return R.error(500, "系统异常");
    }
}